import { useEffect } from 'react';
import { Form, Input, message, Tag, Row, Col, Tabs, Card, Space } from 'antd';
import { useRequest, useLocation, history } from 'umi';
import moment from 'moment';
import ActionBuilder from '../builder/ActionBuilder';
import FormBuilder from '../builder/FormBuilder';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { submitFieldsAdaptor, setFieldsAdaptor } from '../helper';
import styles from '../index.less';
const Page = () => {
  const { TabPane } = Tabs;
  const location = useLocation();
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };

  const [form] = Form.useForm();
  const init = useRequest<{ data: BasicListApi.PageData }>(
    `https://public-api-v2.aspirantzhang.com${location.pathname.replace(
      '/basic-list',
      '',
    )}?X-API-KEY=antd`,
    {
      onError: () => {
        history.goBack();
      },
    },
  );
  useEffect(() => {
    if (init.data) {
      form.setFieldsValue(setFieldsAdaptor(init.data));
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [init.data]);
  const request = useRequest(
    (values: any) => {
      message.loading({ content: '加载中...', key: 'process', duration: 0 });
      const { uri, method, ...formValues } = values;
      return {
        url: `https://public-api-v2.aspirantzhang.com${uri}`,
        method,
        data: {
          ...submitFieldsAdaptor(formValues),
          'X-API-KEY': 'antd',
        },
      };
    },
    {
      manual: true,
      onSuccess: () => {
        message.success({
          content: '更新成功',
          key: 'process',
        });
        history.goBack();
      },
      formatResult: (res: any) => {
        return res;
      },
      throttleInterval: 1000,
    },
  );
  const onFinish = (values: any) => {
    request.run(values);
  };

  const actionHandler = (action: BasicListApi.Action) => {
    switch (action.action) {
      case 'submit':
        form.setFieldsValue({ uri: action.uri, method: action.method });
        form.submit();
        break;
      case 'cancel':
        history.goBack();
        break;
      case 'reset':
        form.resetFields();
        break;
      default:
        break;
    }
  };
  return (
    <PageContainer>
      <Form
        form={form}
        {...layout}
        initialValues={{
          create_time: moment(),
          update_time: moment(),
          status: true,
        }}
        onFinish={onFinish}
      >
        <Row gutter={24}>
          <Col sm={18}>
            <Tabs type="card" className={styles.pageTabs}>
              {(init?.data?.layout?.tabs || []).map((tab: any) => {
                return (
                  <TabPane tab={tab.title} key={tab.title}>
                    <Card>{FormBuilder(tab.data)}</Card>
                  </TabPane>
                );
              })}
            </Tabs>
          </Col>
          <Col sm={6} className={styles.textAlignCenter}>
            {(init?.data?.layout?.actions || []).map((action) => {
              return (
                <Card>
                  <Space>{ActionBuilder(action.data, actionHandler)}</Space>
                </Card>
              );
            })}
          </Col>
        </Row>
        <FooterToolbar
          extra={
            <Tag className={styles.formUpdateTime}>
              update_time:{moment(init.data?.dataSource?.update_time).format('YYYY-MM-DD HH:mm:ss')}
            </Tag>
          }
        >
          {ActionBuilder(init?.data?.layout?.actions[0].data, actionHandler)}
        </FooterToolbar>
        <Form.Item name="uri" key="uri" hidden>
          <Input />
        </Form.Item>
        <Form.Item name="method" key="method" hidden>
          <Input />
        </Form.Item>
      </Form>
    </PageContainer>
  );
};
export default Page;
